package control

import (
	"go_gvm_mini/instructions/base"
	"go_gvm_mini/rtda"
)

type LOOKUP_SWITCH struct {
	defaultOffset int32
	npairs        int32
	matchOffsets  []int32
}

func (ls *LOOKUP_SWITCH) FetchOperands(reader *base.ByteCodeReader) {
	reader.SkipPadding()
	ls.defaultOffset = reader.ReadInt32()
	ls.npairs = reader.ReadInt32()
	ls.matchOffsets = reader.ReadInt32s(ls.npairs * 2)
}

func (self *LOOKUP_SWITCH) Execute(jFrame *rtda.JFrame) {
	key := jFrame.OperandStack().PopInt()
	for i := int32(0); i < self.npairs*2; i += 2 {
		if self.matchOffsets[i] == key {
			offset := self.matchOffsets[i+1]
			base.Branch(jFrame, int(offset))
			return
		}
	}
	base.Branch(jFrame, int(self.defaultOffset))
}
